package model

import (
	"errors"
	"gorm.io/gorm"
)

const Relation_Table = "relationships"

type Relationship struct {
	gorm.Model
	Doctor  uint `json:"doctor"`
	Patient uint `json:"patient"`
}

type TherapeuticRelationship struct {
	Doctor   uint   `json:"doctor"`
	Patients []uint `json:"patients"`
}

func (t *TherapeuticRelationship) Get(db *gorm.DB) error {
	doctor := t.Doctor
	var relationships []Relationship
	err := db.Table(Relation_Table).Where(Eq("doctor", doctor)).Find(&relationships).Error
	if err != nil {
		return err
	}
	for _, relation := range relationships {
		t.Patients = append(t.Patients, relation.Patient)
	}
	return nil
}

func (t *TherapeuticRelationship) Add(db *gorm.DB) error {
	doctor := t.Doctor
	tx := db.Begin()
	for _, patient := range t.Patients {
		user := User{}
		user.ID = patient

		err := user.Get(tx)
		if err != nil {
			tx.Rollback()
			return errors.New("no such patient")
		}

		relationship := &Relationship{
			Doctor:  doctor,
			Patient: patient,
		}
		err = tx.Create(relationship).Error
		if err != nil {
			// 可能是被软删除了，恢复数据
			//db.Unscoped().Model(&productToDelete).Update("DeletedAt", nil) // Restore soft deleted record

			tx.Rollback()
			return err
		}
	}
	tx.Commit()
	return nil
}

func (t *TherapeuticRelationship) Delete(db *gorm.DB) error {
	//doctor := t.Doctor
	return db.Table(Relation_Table).Unscoped().Where(Eq("doctor", t.Doctor)).Where("patient in (?)", t.Patients).Delete(nil).Error
	//tx := db.Begin()
	//for _, patient := range t.Patients {
	//	user := User{}
	//	user.ID = patient
	//
	//	relationship := &Relationship{
	//		Doctor:  doctor,
	//		Patient: patient,
	//	}
	//	err := tx.Where(Eq("patient", patient)).Where(Eq("doctor", doctor)).Delete(relationship).Error
	//	if err != nil {
	//		tx.Rollback()
	//		return err
	//	}
	//}
	//tx.Commit()
	//return nil
}

func (r *Relationship) Delete(db *gorm.DB) error {
	return db.Delete(r).Error
}
